extends Node

@export var spawns: Array[SpawnerInfo] = []

@onready var player = get_tree().get_first_node_in_group("player")

var time = 0


func _on_timer_timeout():
	time += 1
	var enemy_spawners = spawns
	for i in enemy_spawners:
		if time >= i.time_start and time <= i.time_end:
			# 计数器
			if i.spawn_delay_counter < i.enemy_spawn_delay:
				i.spawn_delay_counter += 1
			else: # 添加enemy
				i.spawn_delay_counter = 0
				#var new_enemy = load("res://enemy/enemy.tscn")
				var new_enemy = i.enemy
				var counter = 0
				while counter < i.enemy_num:
					var enemy_spawn = new_enemy.instantiate()
					enemy_spawn.global_position = get_random_position()
					add_child(enemy_spawn)
					counter += 1


func get_random_position():
	var vpr = get_viewport().get_visible_rect().size * randf_range(1.1, 1.4)
	var top_left = Vector2(player.global_position.x - vpr.x / 2, player.global_position.y - vpr.y / 2 )
	var top_right = Vector2(player.global_position.x + vpr.x / 2, player.global_position.y - vpr.y / 2 )
	var bottom_left = Vector2(player.global_position.x - vpr.x / 2, player.global_position.y + vpr.y / 2 )
	var bottom_right = Vector2(player.global_position.x + vpr.x / 2, player.global_position.y + vpr.y / 2 )
	
	var pos_side = ["up", "down", "right", "left"].pick_random()
	var spawner_pos1 = Vector2.ZERO
	var spawner_pos2 = Vector2.ZERO
	
	match pos_side:
		"up":
			spawner_pos1 = top_left
			spawner_pos2 = top_right
		"down":
			spawner_pos1 = bottom_left
			spawner_pos2 = bottom_right
		"left":
			spawner_pos1 = top_left
			spawner_pos2 = bottom_left
		"right":
			spawner_pos1 = top_right
			spawner_pos2 = bottom_right
	
	var x_spawner = randf_range(spawner_pos1.x, spawner_pos2.x)
	var y_spawner = randf_range(spawner_pos1.y, spawner_pos2.y)
	return Vector2(x_spawner, y_spawner)
